package de.golbros.capacitorqrscanner;

import android.content.Intent;
import android.util.Log;
import com.getcapacitor.Logger;
import com.getcapacitor.JSObject;
import com.getcapacitor.NativePlugin;
import com.getcapacitor.Plugin;
import com.getcapacitor.PluginCall;
import com.getcapacitor.PluginMethod;

@NativePlugin(
        requestCodes={CapacitorQRScanner.QR_SCAN} // register request code(s) for intent results
)
public class CapacitorQRScanner extends Plugin {

    protected static final int QR_SCAN = 12345;

    @PluginMethod()
    public void scan(PluginCall call) {
        Log.d("PP", "scan");
        Logger.debug("SCAN");
        saveCall(call);

        Intent intent = new Intent(getActivity(), QRScanner.class);
        startActivityForResult(call, intent, CapacitorQRScanner.QR_SCAN);
    }

    @Override
    protected void handleOnActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d("PP","handle");
        super.handleOnActivityResult(requestCode, resultCode, data);

        PluginCall savedCall = getSavedCall();

        if (savedCall == null) {
            savedCall.reject("Error");
        }
        if (requestCode == QR_SCAN) {
            JSObject o = new JSObject();
            if (data != null) {
                o.put("code", data.getStringExtra("code"));
            } else {
                o.put("code", null);
            }
            savedCall.success(o);
        }
    }

}
